package com.mack.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.mack.config.CronTaskRegistrar;
import com.mack.entity.SysJobPO;
import com.mack.enums.StatusEnum;
import com.mack.service.ISysJobService;
import com.mack.util.SchedulingRunnable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysJobRunnerImpl implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(SysJobRunnerImpl.class);

    @Autowired
    private ISysJobService sysJobService;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;
    @Override
    public void run(String... args) throws Exception {
        // 初始加载数据库里状态为正常的定时任务
        List<SysJobPO> jobList = sysJobService.list(new QueryWrapper<SysJobPO>().eq("job_status", StatusEnum.NORMAL.name()));
        if (CollectionUtils.isNotEmpty(jobList)) {
            for (SysJobPO job : jobList) {
                SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
                cronTaskRegistrar.addCronTask(task, job.getCronExpression());
            }
            logger.info("定时任务已加载完毕...");
        }
    }
}
